import {
  reqGartList,
  reqDeleteCartById,
  reqUpdateCheckedById,
} from "../../api/index";

const state = {
  shopCartList: [],
};
const actions = {
  // 获取购物数据
  async getShopCartList({ commit }) {
    let result = await reqGartList();
    if (result.status == 200) {
      commit("GETSHOPCARTLIST", result.data.data);
    }
  },
  // 删除购物的产品
  async deleteCartListBySkuId({ commit }, skuId) {
    let result = await reqDeleteCartById(skuId);
    if (result.status == 200) {
      return "ok";
      // 代表服务器加入购物车失败
    } else {
      return Promise.reject(new Error("faile"));
    }
  },
  // 更改商品选中状态
  async updateCheckedById({ commit }, { skuId, isChecked }) {
    let result = await reqUpdateCheckedById(skuId, isChecked);
    if (result.status == 200) {
      return "ok";
      // 代表服务器加入购物车失败
    } else {
      return Promise.reject(new Error("faile"));
    }
  },
  // 删除所选中的商品
  deleteAllCheckedCart({ dispatch, state }) {
    // context :小仓库，commit 【提交mutations修改state】 getters 【计算属性】 dispatch 【派发action】state 【当前仓库数据】
    state.shopCartList[0].cartInfoList.forEach((item) => {
      if (item.isChecked == 1) {
        dispatch("deleteCartListBySkuId", item.skuId);
      }
    });
  },
  // 全选or全不选
  updateAllCartChecked({ dispatch, state }, isChecked) {
    state.shopCartList[0].cartInfoList.forEach((item) => {
      dispatch("updateCheckedById", {
        skuId: item.skuId,
        isChecked,
      });
    });
  },
};
const mutations = {
  // 将购物车数据放在state仓库中
  GETSHOPCARTLIST(state, shopCartList) {
    state.shopCartList = shopCartList;
  },
};
const getters = {
  cartList(state) {
    return state.shopCartList[0] || {};
  },
};

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters,
};
